import React, { useMemo, useCallback, useRef, Ref } from 'react';
import { Space, Steps, Button, message } from 'antd';

import ScrollBarLayout from '@/components/ScrollBarLayout';
import { FirstStep, SecondStep, ThirdStep } from './components';
import { OneModal } from '../OneModal';

import { useUploadModal, UploadContext } from './useUploadModal';

import { uploadRequest } from './service';

import { IUploadModalProps } from './type';
import cls from 'classnames';
import './index.less';
import { IOneModalRef } from '../OneModal/type';
import { useRequest } from 'umi';

export const UploadModal: React.FC<IUploadModalProps> = ({ onClose, template, upload, alert, ...otherProps }) => {
  const prefix = 'upload-modal';

  const modalRef: Ref<IOneModalRef> = useRef(null);

  const { state, dispatch } = useUploadModal();

  const steps = [
    {
      title: '上传文件',
    },
    {
      title: '数据校验',
    },
    {
      title: '导入数据',
    },
  ];

  /* 切换step */
  const onSetCurrent = useCallback(
    (current: any) => {
      if (state.uploadLoading) {
        message.error('请等待数据上传完毕，在进行其他操作');
        return;
      } else {
        dispatch({
          type: 'changeCurrent',
          payload: {
            current: current,
          },
        });
      }
    },
    [state.current, state.uploadLoading],
  );

  /* 关闭弹窗 */
  const onCloseModal = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (state.uploadLoading) {
      message.error('请等待数据上传完毕，在进行其他操作');
      return;
    } else {
      if (modalRef) {
        if (modalRef.current) {
          if (modalRef.current.onModalCancel) {
            modalRef.current.onModalCancel(e);
          }
        }
      }
    }
  };

  /* 第二部上传文件 */
  const uploadFile = useRequest(
    (url: string, data: any) => {
      return uploadRequest(url, data);
    },
    {
      manual: true,
      onSuccess: (res) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
          setUploadLoading(false);
          dispatch({
            type: 'setTotal',
            payload: {
              total: res?.obj?.total,
            },
          });
          dispatch({
            type: 'changeCurrent',
            payload: {
              current: 2,
            },
          });
        } else {
          setUploadLoading(false);
          message.error(res?.msg);
        }
      },
    },
  );

  const onRequestFile = (url: string, data: any) => {
    setUploadLoading(true);

    if (url && data) {
      uploadFile.run(url, data);
    } else {
      setUploadLoading(false);
    }
  };

  const setUploadLoading = (load: boolean) => {
    dispatch({
      type: 'uploadLoading',
      payload: {
        uploadLoading: load,
      },
    });
  };

  const footer = useMemo(() => {
    return (
      <div className={cls(prefix + '-footer')}>
        <Space>
          <Button onClick={onCloseModal}>关闭</Button>
          {state.current === 0 && (
            <Button
              onClick={() => {
                if (state.uploadInfo) {
                  onSetCurrent(1);
                } else {
                  message.error('未上传文件或文件解析错误');
                }
              }}
            >
              下一步
            </Button>
          )}
          {state.current === 1 && (
            <>
              <Button
                onClick={() => {
                  onSetCurrent(0);
                }}
                type="primary"
              >
                重新上传
              </Button>
              <Button
                onClick={() => {
                  onRequestFile(upload?.uploadUrl, state.dataList);
                }}
                type="primary"
              >
                下一步
              </Button>
            </>
          )}
        </Space>
      </div>
    );
  }, [state.current, state.uploadInfo]);

  return (
    <OneModal
      width={'40%'}
      ref={modalRef}
      bodyStyle={{
        padding: 0,
      }}
      cancelText="关闭"
      footer={footer}
      closable={false}
      onCancel={onClose}
      maskClosable={false}
      {...otherProps}
    >
      <UploadContext.Provider
        value={{
          ...state,
          dispatch,
        }}
      >
        <div
          className={cls(prefix)}
          style={{
            height: window.screen.height * 0.4,
          }}
        >
          <div className={cls(prefix + '-step')}>
            <Steps current={state.current} size={'small'} items={steps} />
          </div>
          <div className={cls(prefix + '-content')}>
            <ScrollBarLayout>
              <FirstStep prefix={prefix} template={template} upload={upload} alert={alert} />
              <SecondStep prefix={prefix} />
              <ThirdStep prefix={prefix} />
            </ScrollBarLayout>
          </div>
        </div>
      </UploadContext.Provider>
    </OneModal>
  );
};

const getKey = () => {
  return String(Math.random() * 1000000) + '-' + String(Math.random() * 1000000);
};

UploadModal.displayName = `One-modal-${getKey()}-${getKey()}`;
